//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.ServiceModel
{
    using System;
    using System.Web.Http.SelfHost;

    public class PreflightSelfHost : IPreflightSelfHost
    {
        private static readonly object startLock = new object();
        private readonly PreflightSelfHostConfiguration selfHostConfiguration;
        private HttpSelfHostServer server;

        private PreflightSelfHost(PreflightSelfHostConfiguration configuration)
        {
            this.selfHostConfiguration = configuration;
        }

        public bool IsStarted
        {
            get
            {
                return this.server != null;
            }
        }

        public void Start()
        {
            lock (startLock)
            {
                if (this.IsStarted)
                {
                    throw new InvalidOperationException("Server has already started");
                }

                var configuration = new HttpSelfHostConfiguration(this.selfHostConfiguration.ServiceOptions.BaseAddress)
                    {
                        ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None,
                        IncludeErrorDetailPolicy = this.selfHostConfiguration.ErrorDetailPolicy
                    };

                if (this.selfHostConfiguration.ServiceOptions.SecurityMode == PreflightServiceSecurityMode.WindowsAuthentication)
                {
                    configuration.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
                }

                PreflightService.MapHttpRoute(configuration.Routes);
                PreflightService.Initialize(this.selfHostConfiguration.Context, this.selfHostConfiguration.ServiceOptions);
                this.server = new HttpSelfHostServer(configuration);
                this.server.OpenAsync();
            }
        }

        public void Stop()
        {
            if (this.IsStarted)
            {
                try
                {
                    this.server.CloseAsync().Wait();
                    this.server.Dispose();
                    this.server = null;
                }
                catch (ObjectDisposedException)
                {
                }
            }
        }

        public void Dispose()
        {
            this.Stop();
        }

        public static IPreflightSelfHost Create(PreflightSelfHostConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            return new PreflightSelfHost(configuration);
        }
    }
}
